'use client'

import { useState, useEffect } from 'react'
import { Calendar, TrendingUp, Users, FileText, Eye, Download, Clock, BarChart3, Loader2 } from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { analyticsAPI } from '@/lib/api'
import { toast } from 'sonner'

interface AnalyticsOverview {
  totalUsers: number
  totalKnowledgeBases: number
  totalViews: number
  totalLikes: number
  activeUsers: number
  publishedContent: number
}

interface TrendData {
  date: string
  users: number
  views: number
  likes: number
  content: number
}

interface TopContent {
  id: string
  title: string
  type: string
  views: number
  likes: number
  createdAt: string
}

interface UserBehavior {
  pageViews: number
  uniqueVisitors: number
  averageSessionDuration: number
  bounceRate: number
  topPages: Array<{
    path: string
    views: number
    uniqueViews: number
  }>
}

export default function Analytics() {
  const [overview, setOverview] = useState<AnalyticsOverview | null>(null)
  const [trends, setTrends] = useState<TrendData[]>([])
  const [topContent, setTopContent] = useState<TopContent[]>([])
  const [userBehavior, setUserBehavior] = useState<UserBehavior | null>(null)
  const [timeRange, setTimeRange] = useState('7d')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const timeRanges = [
    { value: '7d', label: '最近7天' },
    { value: '30d', label: '最近30天' },
    { value: '90d', label: '最近90天' },
    { value: '1y', label: '最近1年' }
  ]

  // 获取统计数据
  const fetchAnalytics = async () => {
    try {
      setIsLoading(true)
      setError(null)
      
      // 并行获取所有数据
      const [overviewData, trendsData, topContentData, userBehaviorData] = await Promise.all([
        analyticsAPI.getOverview(),
        analyticsAPI.getTrends(timeRange),
        analyticsAPI.getTopContent(),
        analyticsAPI.getUserBehavior()
      ])
      
      setOverview(overviewData)
      setTrends(trendsData)
      setTopContent(topContentData)
      setUserBehavior(userBehaviorData)
    } catch (error: any) {
      console.error('Failed to fetch analytics:', error)
      const errorMessage = error.message || '获取统计数据失败'
      setError(errorMessage)
      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  // 时间范围变化时重新获取数据
  useEffect(() => {
    fetchAnalytics()
  }, [timeRange])

  const getGrowthRate = (current: number | undefined, previous: number | undefined) => {
    if (current === undefined || previous === undefined || previous === 0) return 0
    return ((current - previous) / previous * 100).toFixed(1)
  }

  const formatNumber = (num: number | undefined | null) => {
    if (num === undefined || num === null) return '0'
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
    return num.toString()
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载统计数据中...</span>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={fetchAnalytics}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            重试
          </button>
        </div>
      </div>
    )
  }

  if (!overview || !trends || !topContent || !userBehavior) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center text-muted-foreground">
          暂无统计数据
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">数据统计</h1>
          <p className="text-gray-600 mt-1">系统数据分析和趋势报告</p>
        </div>
        <div className="flex items-center space-x-2">
          <Calendar className="h-4 w-4 text-muted-foreground" />
          <select
            value={timeRange}
            onChange={(e) => setTimeRange(e.target.value)}
            className="px-3 py-2 border border-input rounded-md bg-background text-sm"
          >
            {timeRanges.map(range => (
              <option key={range.value} value={range.value}>
                {range.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* 概览统计 */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <Users className="h-5 w-5 text-blue-600" />
              <div>
                <p className="text-sm text-muted-foreground">总用户数</p>
                <p className="text-2xl font-bold">{formatNumber(overview.totalUsers)}</p>
                {trends.length > 1 && (
                  <p className="text-xs text-green-600">
                    +{getGrowthRate(
                      trends[trends.length - 1].users,
                      trends[trends.length - 2].users
                    )}%
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <FileText className="h-5 w-5 text-green-600" />
              <div>
                <p className="text-sm text-muted-foreground">知识库数量</p>
                <p className="text-2xl font-bold">{formatNumber(overview.totalKnowledgeBases)}</p>
                {trends.length > 1 && (
                  <p className="text-xs text-green-600">
                    +{getGrowthRate(
                      trends[trends.length - 1].content,
                      trends[trends.length - 2].content
                    )}%
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <Eye className="h-5 w-5 text-purple-600" />
              <div>
                <p className="text-sm text-muted-foreground">总浏览量</p>
                <p className="text-2xl font-bold">{formatNumber(overview.totalViews)}</p>
                {trends.length > 1 && (
                  <p className="text-xs text-green-600">
                    +{getGrowthRate(
                      trends[trends.length - 1].views,
                      trends[trends.length - 2].views
                    )}%
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <TrendingUp className="h-5 w-5 text-orange-600" />
              <div>
                <p className="text-sm text-muted-foreground">总点赞数</p>
                <p className="text-2xl font-bold">{formatNumber(overview.totalLikes)}</p>
                {trends.length > 1 && (
                  <p className="text-xs text-green-600">
                    +{getGrowthRate(
                      trends[trends.length - 1].likes,
                      trends[trends.length - 2].likes
                    )}%
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 趋势图表 */}
      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">用户增长趋势</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {trends.map((day, index) => (
                <div key={day.date} className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">{day.date}</span>
                  <div className="flex items-center space-x-4">
                    <span className="text-sm">{day.users} 用户</span>
                    <div className="w-32 bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ 
                          width: `${trends.length > 0 && Math.max(...trends.map(d => d.users)) > 0
                            ? (day.users / Math.max(...trends.map(d => d.users))) * 100
                            : 0
                          }%` 
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">内容发布趋势</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {trends.map((day, index) => (
                <div key={day.date} className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">{day.date}</span>
                  <div className="flex items-center space-x-4">
                    <span className="text-sm">{day.content} 文章</span>
                    <div className="w-32 bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-green-600 h-2 rounded-full transition-all duration-300"
                        style={{ 
                          width: `${trends.length > 0 && Math.max(...trends.map(d => d.content)) > 0
                            ? (day.content / Math.max(...trends.map(d => d.content))) * 100
                            : 0
                          }%` 
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 热门内容 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">热门内容排行</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {topContent.map((content, index) => (
              <div
                key={content.id}
                className="flex items-center justify-between p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors"
              >
                <div className="flex items-center space-x-4">
                  <Badge variant="outline" className="w-8 h-8 flex items-center justify-center">
                    {index + 1}
                  </Badge>
                  <div>
                    <h3 className="font-medium">{content.title}</h3>
                    <div className="flex items-center space-x-4 mt-1 text-sm text-muted-foreground">
                      <span className="flex items-center space-x-1">
                        <Eye className="h-4 w-4" />
                        <span>{formatNumber(content.views)}</span>
                      </span>
                      <span className="flex items-center space-x-1">
                        <TrendingUp className="h-4 w-4" />
                        <span>{formatNumber(content.likes)}</span>
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {content.type}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  <div className="text-sm font-medium">
                    {topContent.length > 0 && topContent[0].views > 0 
                      ? ((content.views / topContent[0].views) * 100).toFixed(1)
                      : '0.0'
                    }%
                  </div>
                  <div className="text-xs text-muted-foreground">热度指数</div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 用户行为分析 */}
      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">页面访问统计</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="text-center">
                  <p className="text-2xl font-bold text-blue-600">{formatNumber(userBehavior.pageViews)}</p>
                  <p className="text-sm text-muted-foreground">页面浏览量</p>
                </div>
                <div className="text-center">
                  <p className="text-2xl font-bold text-green-600">{formatNumber(userBehavior.uniqueVisitors)}</p>
                  <p className="text-sm text-muted-foreground">独立访客</p>
                </div>
              </div>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm">平均会话时长</span>
                  <span className="text-sm font-medium">{userBehavior.averageSessionDuration}秒</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">跳出率</span>
                  <span className="text-sm font-medium">{userBehavior.bounceRate}%</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">热门页面</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {userBehavior.topPages.map((page, index) => (
                <div key={page.path} className="flex items-center justify-between">
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="w-6 h-6 flex items-center justify-center text-xs">
                      {index + 1}
                    </Badge>
                    <span className="text-sm font-medium truncate max-w-32">{page.path}</span>
                  </div>
                  <div className="text-right">
                    <div className="text-sm font-medium">{formatNumber(page.views)}</div>
                    <div className="text-xs text-muted-foreground">{formatNumber(page.uniqueViews)} 独立</div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 周度趋势 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">增长趋势详情</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left py-2 font-medium">日期</th>
                  <th className="text-left py-2 font-medium">新增用户</th>
                  <th className="text-left py-2 font-medium">新增内容</th>
                  <th className="text-left py-2 font-medium">总浏览量</th>
                  <th className="text-left py-2 font-medium">总点赞</th>
                  <th className="text-left py-2 font-medium">增长率</th>
                </tr>
              </thead>
              <tbody>
                {trends.map((week, index) => {
                  const prevWeek = trends[index - 1]
                  const userGrowth = prevWeek ? getGrowthRate(week.users, prevWeek.users) : 0
                  const contentGrowth = prevWeek ? getGrowthRate(week.content, prevWeek.content) : 0
                  
                  return (
                    <tr key={week.date} className="border-b border-border">
                      <td className="py-2">{week.date}</td>
                      <td className="py-2">{week.users}</td>
                      <td className="py-2">{week.content}</td>
                      <td className="py-2">{formatNumber(week.views)}</td>
                      <td className="py-2">{formatNumber(week.likes)}</td>
                      <td className="py-2">
                        <Badge 
                          variant={Number(userGrowth) >= 0 ? "default" : "secondary"}
                          className={Number(userGrowth) >= 0 ? "bg-green-100 text-green-800" : ""}
                        >
                          {Number(userGrowth) >= 0 ? '+' : ''}{userGrowth}%
                        </Badge>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
